import { defineStore } from 'pinia';
import { ref, watch } from 'vue';

export const useThemeStore = defineStore('theme', () => {
  // 1. 主题色状态
  const defaultPrimaryColor = '#E65E88'; // 默认粉色
  const primaryColor = ref(localStorage.getItem('primaryColor') || defaultPrimaryColor);

  function setPrimaryColor(newColor) {
    if (typeof newColor === 'string' && /^#([0-9A-F]{3}){1,2}$/i.test(newColor)) {
      primaryColor.value = newColor;
    }
  }

  watch(primaryColor, (newColor) => {
    // 更新 CSS 变量
    document.documentElement.style.setProperty('--primary-color', newColor);
    // 持久化
    localStorage.setItem('primaryColor', newColor);
    console.log('Primary color updated:', newColor);
  }, { immediate: true }); // 立即执行以应用初始值

  // 2. 亮/暗模式状态
  const defaultMode = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
  const themeMode = ref(localStorage.getItem('themeMode') || defaultMode); // 'light' or 'dark'

  function setThemeMode(mode) {
    if (mode === 'light' || mode === 'dark') {
      themeMode.value = mode;
    }
  }

  function toggleThemeMode() {
    setThemeMode(themeMode.value === 'light' ? 'dark' : 'light');
  }

  watch(themeMode, (newMode, oldMode) => {
    const htmlEl = document.documentElement;
    if (oldMode) {
      htmlEl.classList.remove(`${oldMode}-theme`);
    }
    htmlEl.classList.add(`${newMode}-theme`);
    // 持久化
    localStorage.setItem('themeMode', newMode);
    console.log('Theme mode updated:', newMode);
  }, { immediate: true }); // 立即执行以应用初始模式

  return {
    primaryColor,
    setPrimaryColor,
    themeMode,
    setThemeMode,
    toggleThemeMode,
  };
});